package com.test1.administrator.website.dao;


import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import com.test1.administrator.website.data.MyDataBaseHelper;
import com.test1.administrator.website.entity.Website;
import com.test1.administrator.website.util.websiteIsNullException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/8.
 */

public class DBOperator {
    private Context context;
    private MyDataBaseHelper myHelper;
    private SQLiteDatabase db;
    private List<Map<String,Website>> list;

    public DBOperator(Context context) {
        this.context = context;
        myHelper=new MyDataBaseHelper(context,"websitedb",null,1);
        db=myHelper.getWritableDatabase();

    }

    //     写入数据
    public void insert(String name,String website) {
        ContentValues value=new ContentValues();
        if(name==null || "".equals(name)){
            name="默认网站";
        }
        value.put("name",name);
        value.put("website",website);
//        // TODO: 2017/5/8
        long b=db.insert("website",null,value);
    }

//    更新数据
    public void update(String id,Website website){
        String name=website.getName();
        String web=website.getSite();
        if(name==null || "".equals(name)){
            name="默认网站";
        }
        ContentValues cv=new ContentValues();
        cv.put("name",name);
        cv.put("website",web);
        String[] args={id};
        db.update("website",cv,"id=?",args);
    }

//    查询数据
    public List<Map<String,Website>> query(){
//        // TODO: 2017/5/9
        list=new ArrayList<>();
        Cursor cursor=db.query("website",null,null,null,null,null,null);
        while(cursor.moveToNext()){
//            // TODO: 2017/5/9
            Map<String,Website> m=new HashMap<>();
            try {
                Website w=new Website(cursor.getString(1),cursor.getString(2));
                m.put(cursor.getString(0),w);
                list.add(m);
            } catch (websiteIsNullException e) {
                e.printStackTrace();
            }
        }
        cursor.close();
        return list;
    }

    public void delete(String id){

        db.delete("website","id=?",new String[]{id});
    }


}
